package com.catmiw.stock.old2008;

import java.util.*;
import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2007</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */
public class TradeDayKeeper {
    private static TradeDayKeeper instance = new TradeDayKeeper();
    private static ArrayList<Integer> days = null;
    private TradeDayKeeper() {
    }

    public static TradeDayKeeper getInstance() {
        return instance;
    }

    public static int getStart(int end, int interval) {
        if (days == null) {
            days = new ArrayList<Integer>();
            getDayFromFile(PropertyManager.getProperty("SHShareIndexDiaryFile"));
        }
        for (int i = days.size() - 1; i >= 0; i--) {
            if (days.get(i).intValue() == end) {
                if ((i - interval + 1) >= 0) {
                    return days.get(i - interval + 1).intValue();
                } else {
                    return days.get(0).intValue();
                }
            }
        }
        return 0;
    }

    public static boolean isTradeDay(int date) {
        if (days == null) {
            days = new ArrayList<Integer>();
            getDayFromFile(PropertyManager.getProperty("SHShareIndexDiaryFile"));
        }
        return Collections.binarySearch(days, date) >= 0;
    }

    private static void getDayFromFile(String fn) {
        int rtn = 0;
        BufferedInputStream bi = null;
        try {
            bi = new BufferedInputStream(new
                                         FileInputStream(fn));
            byte[] d = new byte[32];
            byte[] dc = new byte[4];
            while (bi.read(d) >= 0) {
                for (int i = 0; i < 4; i++) {
                    dc[3 - i] = d[i];
                }
                rtn = CommonUtil.bytesToInt(dc);
                days.add(rtn);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                bi.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }
}
